var svg = new drawSvgFigure("#svg");
svg.drag();
var svgGroup = svg.setGroup();// 创建一个svg元素组，将所有的元素放在里面，方便整体移动位置
var subStation = [];// 站名
var actTimeInfo = [];// 默认显示的保护和断路器动作时间信息
var allActInfo = [];// 所有保护和断路器动作时间信息
var errorList = [];// 显示错误的配置信息
var time1 = 0;
var time2 = 50;
var time3 = 100;
var time4 = 950;
var time5 = 1000;
var finalActTime = 0;// 最后动作时间
var allFinalActTime = 0;// 所有时间中的最大值
var defaultFinalActTime = 0;// 默认显示中的最大值
var iframe = $(window.parent.document).find("#iframePage");
var result = undefined;
var drawData=[];//画时序图需要的数据
var svgWidth=0;
$(function() {
	svgWidth = Number($("#svg").parent().width())-150;
	getActInfo();// 获取动作时间序列
	if (iframe.length == 1) {
		parent.reinitIframe();
	}
	$("#saveAsImage").click(function() {
		// 保存为图片
		saveAsImage();
	});
	$("#refresh").click(function() {
		svgGroup.remove();
		svgGroup = svg.setGroup();
		$("#svg").width("2000").height("500");
		svgWidth = Number($("#svg").parent().width())-150;
		finalActTime = defaultFinalActTime;
		drawData=[];
		$.extend(true,drawData,actTimeInfo);
		zoom.refreshInit();
		initTimeLineData(1);
		if (iframe.length == 1) {
			parent.reinitIframe();
		}
	});
	$("#seeAllInfo").click(function() {
		$(this).addClass("selected");
		svgGroup.remove();
		svgGroup = svg.setGroup();
		svgWidth = Number($("#svg").parent().width())-150;
		$("#svg").width("2000").height("500");
		finalActTime = allFinalActTime;
		drawData=[];
		$.extend(true,drawData,allActInfo);
		zoom.refreshInit();
		initTimeLineData(1);
		if (iframe.length == 1) {
			parent.reinitIframe();
		}
	});
});

function saveAsImage() {
	var svgXml = $('#actSvg').html().trim();
	canvg("canvas", svgXml);
	var a = document.createElement('a');
	a.href = canvas.toDataURL('image/png'); // 将画布内的信息导出为png图片数据
	a.download = "我的下载"; // 设定下载名称
	a.click(); // 点击触发下载
}

// [{"stationName":"思茅变","value":{time1:[name,act,phase],time1:[name,act,phase]},"error":[]}]
function getActInfo() {
	var actTimeList = document.getElementById("form10:actTimeList");
	if (actTimeList != null && typeof (actTimeList) != 'undefined') {
		actTimeList = actTimeList.value;
	} else {
		return;
	}
	if (actTimeList != "") {
		result = JSON.parse(actTimeList);
	}
	if (!$.isEmptyObject(result)) {
		$("#svg").width("2000").height("500");
		$(".tools").css("display", "block");
		if (document.getElementById("noDetails")) {
			$("#noDetails").remove();
		}
		groupTime(result);
		defaultFinalActTime = getMaxTime(actTimeInfo);
		allFinalActTime = getMaxTime(allActInfo);
		finalActTime = defaultFinalActTime;
		// showErrorMessage();
		$.extend(true,drawData,actTimeInfo);
		initTimeLineData(1);
	} else {
		$("#svg").height(20);
		$(".tools").css("display", "none");
		if (document.getElementById("noDetails")) {

		} else {
			var span = $("<span id='noDetails'>无详细信息</span>").css({
				"display" : "block",
				"color" : "grey",
				"font-size":"15px",
			    "margin": ".1em 44px .2em -85px"
			}).appendTo($("#actSvg"));
		}
	}
}
// 找最大值
function getMaxTime(timeArr) {
	var maxTime = 0;
	for ( var i in timeArr) {
		for ( var time in timeArr[i]) {
			var t = Number(time) ;
			if (t > maxTime) {
				maxTime = t;
			}
		}
	}
	return maxTime;
}
//对数据分组
function groupTime(data) {
	for ( var i in data) {
		subStation.push(data[i].station);//站点名称
		actTimeInfo.push(formtterTime(data[i].value));//只存主保护，断路器保护，断路器
		errorList.push(data[i].error);
		allActInfo.push(formtterTime(data[i].totalVal));//存放所有动作信息
	}
}
//处理数据，微秒全部转换为毫秒并去掉小数，合并数据{time:[[str,descStr],[str,descStr]]}
function formtterTime(timeMap){
	var newTimeMap={};
	for(var time in timeMap){
		var t = Number((Number(time) / 1000).toFixed(0));
		var faultInfo=timeMap[time];
		var newTimeArr=[];
		for(var i in faultInfo){
			var phaseArr = faultInfo[i][2].split("").sort().join("");// 对相别进行排序
			var str = faultInfo[i][0] + faultInfo[i][1] + phaseArr;
			var descstr = faultInfo[i][3];
			newTimeArr.push([str,descstr]);
		}
		newTimeMap[t]=newTimeArr;
	}
	return newTimeMap;
}

function showErrorMessage() {
	for ( var i in errorList) {
		if (errorList[i].length != 0) {
			$("#errorInfo").css("display", "block");
			var str = "";
			var div = $("<div class='info-box-content'></div>").appendTo($("#errorInfo"));
			for ( var j in errorList[i]) {
				str += errorList[i][j] + " ; ";
			}
			div.html(subStation[i] + ":" + "<span style='color:red'>" + str + "</span>");
			if (errorList[1].length == 0) {
				$(div).css("line-height", "50px");
			}
		}
	}
}
// 画刻度
var sy = 110;// 时间轴起始点纵坐标,初始值在30
var color = "#696969";
var txtPos = [];// 存放所有红色字体的横坐标,以及时间轴刻度的坐标
function drawScale(ratio, timeRatio, time1, time2, sx) {
	for (var i = 1; i <= (time2 - time1) / ratio; i++) {
		var x = ratio * i * timeRatio + sx;
		var time = time1 + ratio * i;
		var timeStr = time.toString();
		if (timeStr == "10" || timeStr == "40" || timeStr == "50" || timeStr == "100" || timeStr == "500"
				|| timeStr == "1000" || timeStr == "1500" || timeStr == "2000") {
			svgGroup.add(svg.drawLine(x, sy, x, sy - 15).attr({
				"stroke" : color,
				"stroke-width" : 1
			}));
			svgGroup.add(svg.drawText(x - 8, sy + 15, time).attr({
				fill : color,
				"font-size":"16"
			}));
			$("#span").html(timeStr);
			var tLen = $("#span").width();
			txtPos.push([ x - 8, x - 8 + tLen ]);
		} else {
			svgGroup.add(svg.drawLine(x, sy, x, sy - 10).attr({
				"stroke" : color
			}));
		}
	}
}
//判断数据集中在哪个范围  true为集中在950-1000
var gt1000=10000;//大于1000的最小数字
var lt1000=950;//大于950小于1000的最大值
function getDataRange(){
	var num950=0;//950-1000
	var num1000=0;//1000+ 
	var faultInfo = drawData[0];//只判断一个站
	for(var time in faultInfo){
		var t = Number(time);
		if(t>1000){
			num1000++;
			if(t<gt1000){
				gt1000=t;
			}
		}else if(t>950&&t<=1000){
			num950++;
			if(t>lt1000){
				lt1000=t;
			}
		}
	}
	return (num950>=num1000);
	
}
//判断最大值在哪个区域内w1:0-50  w2:50-100  w3:100-950  w4:950-1000  w5:1000+   
var w1 = 0, w2 = 0, w3 = 0, w4 = 0,w5=0,timeLineNum=0;//时间轴段数;
var ratio2 = 10;// w2最小刻度
var ratio4 = 100;// w4最小刻度
var ratio5 = 200;// w5最小刻度
// 以50,100,950,1000为分界时间点分五段画时间轴
function initTimeLineData(timeLineScale) {
	svgWidth = svgWidth*timeLineScale;
	if (finalActTime > time5) {
		w1 = svgWidth * 2.5 / 8;
		w2 = svgWidth * 1 / 8;
		w3 = svgWidth * 1 / 8;
		//需要判断数据集中在w4还是w5
		if(getDataRange()){
			time5=Number(lt1000.toFixed(0));
			w4 = svgWidth * 2.5 / 8;
			w5 = svgWidth * 1 / 8;
			ratio4=2;
		}else{
			if(finalActTime!=gt1000){
				time5=Number(gt1000.toFixed(0));
				ratio5 = 10;// 最小刻度
			}
			w4 = svgWidth * 1 / 8;
			w5 = svgWidth * 2.5 / 8;
		}
		timeLineNum = 5;
	}else if (finalActTime > time4) {
		time5=Number(finalActTime.toFixed(0));
		w1 = svgWidth * 3 / 8;
		w2 = svgWidth * 1 / 8;
		w3 = svgWidth * 1 / 8;
		w4 = svgWidth * 3 / 8;
		ratio4=2;
		timeLineNum = 4;
	} else if (finalActTime > time3) {
		time4 = Number(finalActTime.toFixed(0));
		w1 = svgWidth * 3 / 5;
		w2 = svgWidth * 1 / 5;
		w3 = svgWidth * 1 / 5;
		ratio2 = 5;// 最小刻度
		timeLineNum = 3;
	} else if (finalActTime > time2) {
		w1 = svgWidth * 3 / 5;
		w2 = svgWidth * 2 / 5;
		ratio2 = 2;// 最小刻度
		timeLineNum = 2;
	} else {
		w1 = svgWidth;
		timeLineNum = 1;
	}
	drawTimeLine();
}
function drawTimeLine(){
	txtPos = [];
	var title = svg.drawText(0, sy, "时间轴/ms").attr({
		fill : "black",
		"font-size":"16"
	});
	svgGroup.add(title);
	// 第一段时间节点在50以内的
	var sx1 = 80;// 时间轴起始点横坐标
	var ex1 = sx1 + w1;// 时间轴结束点横坐标
	var ey = sy;// 时间轴结束点纵坐标
	var timeLine1 = svg.drawLine(sx1, sy, ex1, ey).attr({
		"stroke" : color,
		"stroke-width" : 2
	});
	svgGroup.add(timeLine1);
	var timeRatio1 = (ex1 - sx1) / (time2 - time1);
	// 画刻度线
	var ratio1 = 2;// 最小刻度
	drawScale(ratio1, timeRatio1, time1, time2, sx1);
	if (timeLineNum >= 2) {
		// 第二段,50-100
		var sx2 = ex1;// 时间轴起始点横坐标
		var ex2 = sx2 + w2;// 时间轴结束点横坐标
		var timeLine2 = svg.drawLine(sx2, sy, ex2, ey).attr({
			"stroke" : color,
			"stroke-width" : 2
		});
		svgGroup.add(timeLine2);
		var timeRatio2 = (ex2 - sx2) / (time3 - time2);
		drawScale(ratio2, timeRatio2, time2, time3, sx2);
	}
	if (timeLineNum >= 3) {
		// 第三段100-950
		var sx3 = ex2;
		var ex3 = sx3 + w3;
		var timeLine3 = svg.drawLine(sx3, sy, ex3, ey).attr({
			"stroke" : color,
			"stroke-width" : 2
		});
		svgGroup.add(timeLine3);
		var timeRatio3 = (ex3 - sx3) / (time4 - time3);
		var ratio3 = 100;// 最小刻度
		drawScale(ratio3, timeRatio3, time3, time4, sx3);
	}
	if (timeLineNum >= 4) {
		// 第四段950-1000
		var sx4 = ex3;
		var ex4 = sx4 + w4;
		var timeLine4 = svg.drawLine(sx4, sy, ex4, ey).attr({
			"stroke" : color,
			"stroke-width" : 2
		});
		svgGroup.add(timeLine4);
		var timeRatio4 = (ex4 - sx4) / (time5 - time4);
		// 第四段950+，画刻度
		drawScale(ratio4, timeRatio4, time4, time5, sx4);
	}
	if (timeLineNum == 5) {
		// 第五段1000+
		var sx5 = ex4;
		var ex5 = sx5 + w5;
		var timeLine5 = svg.drawLine(sx5, sy, ex5, ey).attr({
			"stroke" : color,
			"stroke-width" : 2
		});
		svgGroup.add(timeLine5);
		var timeRatio5= (ex5 - sx5) / (finalActTime - time5);
		// 第五段1000+，画刻度
		drawScale(ratio5, timeRatio5, time5, finalActTime, sx5);
	}
	// 画时序图
	drawActTime(sx1, sx2, sx3, sx4,sx5, timeRatio1, timeRatio2, timeRatio3, timeRatio4,timeRatio5);
}
// 画时序图，根据总长和总时间按比例，在时间轴上取点
function drawActTime(sx1, sx2, sx3, sx4,sx5, timeRatio1, timeRatio2, timeRatio3, timeRatio4, timeRatio5) {
	var scaleTxtColor=color;
	var rectH = 35;// 矩形高
	var rectW = 70;// 矩形宽
	var minRectPos = 0;// 矩形框最小纵坐标
	var maxRectPos = 170;// 矩形框最大纵坐标
	var maxRectPosX = 2000;// 矩形框最大横坐标
	// 先画上面再画下面，后画该站的动作信息
	for (var i = 0; i < drawData.length; i++) {
		if (!$.isEmptyObject(drawData[0])) {
			var station1 = svg.drawText(0, sy - 90, subStation[0]).attr({
				fill : "black",
				"font-size":"16"
			});
			svgGroup.add(station1);
		}
		if (!$.isEmptyObject(drawData[1])) {
			// 站2
			var station2 = svg.drawText(0, sy + 100, subStation[1]).attr({
				fill : "black",
				"font-size":"16"
			});
			svgGroup.add(station2);
		}
		var rectLeftArr = [];// 存放同侧所有矩形框的left值和距离时间轴的高度
		var rectLeft = 0;
		var dotLeft = 0;
		var faultInfo = drawData[i];
		var ArrowLineLength = 30;
		for ( var time in faultInfo) {
			var t =Number(time) ;
			if (t <= time2) {
				var endX = (t - time1) * timeRatio1 + sx1;
			} else if (t <= time3) {
				var endX = (t - time2) * timeRatio2 + sx2;
			} else if (t <= time4) {
				var endX = (t - time3) * timeRatio3 + sx3;
			} else if (t <= time5) {
				var endX = (t - time4) * timeRatio4 + sx4;
			} else {
				var endX = (t - time5) * timeRatio5 + sx5;
			}
			var startX = endX;
			$("#span").html(t.toString());// 判断时间宽度
			var fontLen = $("#span").width();
			if (i == 0) {
				// 站1画上面
				var endY = sy - 22;
				var redLine = svg.drawLine(endX, endY + 12, endX, endY + 22).attr({
					"stroke" : scaleTxtColor,
					"stroke-width" : 1
				});
			} else {
				// 站2画下面
				var endY = sy + 22;
				var redLine = svg.drawLine(endX, endY - 30, endX, endY - 20).attr({
					"stroke" :scaleTxtColor,
					"stroke-width" : 1
				});
			}
			var tx = endX - 10;
			var ty = sy+15;
			dotLeft = tx + fontLen + 7;
			for ( var j in faultInfo[time]) {
				var g = svg.setGroup();
				// 比较判断红色坐标值是否要显示，如果没有重叠就显示，否则就不显示。
				for (var k = 0; k < txtPos.length; k++) {
					if ((tx <= txtPos[k][0] && txtPos[k][0] <= dotLeft)
							|| (tx <= txtPos[k][1] && txtPos[k][1] <= dotLeft)
							|| (txtPos[k][0] <= tx && txtPos[k][1] >= dotLeft)) {
						break;
					} else if (k == txtPos.length - 1) {
						var redTxt = svg.drawText(tx, ty, t).attr({
							"fill" : scaleTxtColor,
							"font-size" : "16"
						});
						g.add(redTxt);
						txtPos.push([ tx, dotLeft ]);
					}
				}
				var str = faultInfo[time][j][0];
				var descstr = faultInfo[time][j][1];
				// 根据文本重新计算矩形框的宽度，保证其不换行
				$("#span").html(str);
				var strWidth = $("#span").width();
				rectW = strWidth + 20;
				var rectStartX = startX - rectW / 2;
				if (rectStartX < 0) {
					rectStartX -= rectStartX;
				}
				ArrowLineLength = 30;
				// 起初箭头线的长度是30，依次比较判断是否会有矩形框重叠，如果有重叠，就增大长度。
				for (var k = 0; k < rectLeftArr.length; k++) {
					if (ArrowLineLength == rectLeftArr[k][1]) {
						if (endX - rectW / 2 < rectLeftArr[k][0]) {
							ArrowLineLength += 40;
							k = 0;
						}
					}
				}
				if (i == 0) {
					// 站1画上面
					var startY = endY - ArrowLineLength;
					var rectStartY = endY - ArrowLineLength - rectH;
				} else {
					// 站2画下面
					var startY = endY + ArrowLineLength;
					var rectStartY = endY + ArrowLineLength;
				}
				var arrowLine = svg.drawArrowLine(startX, startY, endX, endY);
				rectLeft = endX + rectW / 2;
				rectLeftArr.push([ rectLeft, ArrowLineLength ]);
				// 矩形框
				var rect = svg.drawRect(rectStartX, rectStartY, rectW, rectH).data("time", descstr).hover(function(e) {
					var mousePos = getMousePosition(e);
					var strd = this.data("time");
					var brNum = strd.split("br").length;
					tipDiv.css({
						"height" : 30 * brNum,
						"display" : "block",
						"left" : mousePos.x + 10,
						"top" : mousePos.y - 10
					}).html(this.data("time"));
				}, function() {
					$("#tip").hide();
				});
				//记录最右边位置
				if(maxRectPosX<rectStartX+rectW){
					maxRectPosX=rectStartX+rectW+150;
				}
				// 矩形框内的文本
				var txt = svg.drawText(rectStartX + 5, rectStartY + 23, str).attr({
					"font-size":"16"
				}).data("time", descstr).hover(function(e) {
					var mousePos = getMousePosition(e);
					var strd = this.data("time");
					var brNum = strd.split("br").length;
					tipDiv.css({
						"height" : 30 * brNum,
						"display" : "block",
						"left" : mousePos.x + 10,
						"top" : mousePos.y - 10
					}).html(this.data("time"));
				}, function() {
					$("#tip").hide();
				});
				// 右上角关闭按钮
				var closeBtn = svg.drawText(rectStartX + rectW - 8, rectStartY + 10, "x").data("text",{"time":t,"name":str,"stationNO":i}).hover(function() {
					this.addClass("mouseon");
				}, function() {
					this.removeClass("mouseon");
				}).click(function() {
					this.parent().remove();
					removeDrawData(this.data("text"));//移除相应的数据，防止在放缩重新渲染时把移除的部分给渲染出来
				});
				g.add(redLine, arrowLine, rect, txt, closeBtn);
				svgGroup.add(g);
				// 判断上面矩形框是否超出画布范围，如果上面超出，就整体下移，或者下面超出就增加svg高度
				if (rectStartY < minRectPos) {
					minRectPos = rectStartY-50;
				}
				if (rectStartY + rectH > maxRectPos) {
					maxRectPos = rectStartY + rectH + 150;
				}
			}
		}
	}
	svgGroup.transform(svg.translate(0, -minRectPos));
	$("#svg").height(maxRectPos - minRectPos);
	$("#svg").width(maxRectPosX+500);
	$("#actSvg").css({
		"height" : maxRectPos - minRectPos,
		"overflow" : "hidden"
	});
	if (iframe.length == 1) {
		parent.reinitIframe();
	}
}
//点叉号同时删除数组中的数据
function removeDrawData(selectedDataObj){
	var selectedStatData=drawData[selectedDataObj.stationNO][selectedDataObj.time];
	for(var i in selectedStatData){
		if(selectedDataObj.name==selectedStatData[i][0]){
			if(selectedStatData.length>1){
				//如果不止这一个元素
				selectedStatData.splice(i,1);
			}else{
				//如果只有这一个元素要把这一项全部删除
				delete drawData[selectedDataObj.stationNO][selectedDataObj.time];
			}
		}
	}
}
// 提示框
var tipDiv = $("<div></div>").attr("id", "tip").css({
	"width" : 90,
	"height" : 30,
	"background" : "rgba(0,0,0,.5)",
	"color" : "white",
	"font-size":"20px",
	"text-align" : "center",
	"position" : "absolute"
}).appendTo("body").hide();
// 获取鼠标位置
function getMousePosition(e) {
	var ev = e || window.event;
	if (ev.pageX || ev.pageY) {
		return {
			x : ev.pageX,
			y : ev.pageY
		};
	}
	return {
		x : ev.clientX + doucument.body.scrollLeft - document.body.clientLeft,
		y : ev.clentY + document.body.scrollTop - document.body.clientTop
	};
}

function resizeHtml() {
	var waveframe = document.getElementById("svg");
	if (!$.isEmptyObject(result)) {
		svgGroup.remove();
		svgGroup = svg.setGroup();
		$("#svg").width("2000").height("500");
//		finalActTime = defaultFinalActTime;
//		drawData=[];
//		$.extend(true,drawData,actTimeInfo);
//		zoom.refreshInit();
		svgWidth = Number($("#svg").parent().width())-150;
		initTimeLineData(zoom.scale);
		if (iframe.length == 1) {
			parent.reinitIframe();
		}
	} else {
		$("#svg").height(20);
		$(".tools").css("display", "none");
		if (document.getElementById("noDetails")) {
		} else {
			var span = $("<span id='noDetails'>无详细信息</span>").css({
				"display" : "block",
				"color" : "grey",
				"font-size":"15px",
				"margin": ".1em 44px .2em -85px"
			}).appendTo($("#actSvg"));
		}
	}
}

var zoom={
	scale:1,
	up:function(){
		this.scale=1.1;
		this.reDraw();
	},
	down:function(){
		this.scale=0.9;
		this.reDraw();
	},
	reDraw:function(){
		svgGroup.remove();
		svgGroup = svg.setGroup();
		this.refreshInit();
		finalActTime=getMaxTime(drawData);
		initTimeLineData(this.scale);
	},
	refreshInit:function(){
		w1 = 0, w2 = 0, w3 = 0, w4 = 0,w5=0,timeLineNum=0;//时间轴段数;
		ratio2 = 10;// w2最小刻度
		ratio4 = 100;// w4最小刻度
		ratio5 = 200;// w5最小刻度
	}
};

	$("#actSvg").mousewheel(function (event, delta) {  
		if (!event||drawData.length==0) event = window.event; 
		else{
			//上滚是放大1，下滚缩小-1
			if(delta>0){
				zoom.up();
			}else{
				zoom.down();
			}
		}
		return false; 
	}); 


